const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');
const WebSocket = require('ws');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// 创建必要的目录
const hlsDir = path.join(__dirname, 'public', 'hls');
if (!fs.existsSync(hlsDir)) {
    fs.mkdirSync(hlsDir, { recursive: true });
}

// 存储FFmpeg进程
let ffmpegProcess = null;

// 配置RTSP流
const rtspConfig = {
    url: process.env.RTSP_URL || 'rtsp://admin:admin@192.168.1.100:554/stream1',
    hlsPath: path.join(hlsDir, 'stream.m3u8'),
    segmentDuration: 2,
    segmentMaxFiles: 10
};

// 启动RTSP到HLS转换
function startRTSPToHLS() {
    if (ffmpegProcess) {
        ffmpegProcess.kill();
    }

    console.log('Starting RTSP to HLS conversion...');
    console.log('RTSP URL:', rtspConfig.url);

    ffmpegProcess = ffmpeg(rtspConfig.url)
        .inputOptions([
            '-rtsp_transport tcp',
            '-i', rtspConfig.url
        ])
        .outputOptions([
            '-c:v copy',
            '-c:a aac',
            '-f hls',
            '-hls_time', rtspConfig.segmentDuration,
            '-hls_list_size', rtspConfig.segmentMaxFiles,
            '-hls_flags delete_segments',
            '-hls_segment_filename', path.join(hlsDir, 'segment_%03d.ts')
        ])
        .output(rtspConfig.hlsPath)
        .on('start', (commandLine) => {
            console.log('FFmpeg started:', commandLine);
        })
        .on('progress', (progress) => {
            console.log('Processing: ' + progress.percent + '% done');
        })
        .on('stderr', (stderrLine) => {
            console.log('FFmpeg stderr:', stderrLine);
        })
        .on('error', (err) => {
            console.error('FFmpeg error:', err);
        })
        .on('end', () => {
            console.log('FFmpeg process ended');
        })
        .run();
}

// 停止FFmpeg进程
function stopRTSPToHLS() {
    if (ffmpegProcess) {
        ffmpegProcess.kill();
        ffmpegProcess = null;
        console.log('FFmpeg process stopped');
    }
}

// API路由
app.get('/api/status', (req, res) => {
    res.json({
        status: ffmpegProcess ? 'running' : 'stopped',
        rtspUrl: rtspConfig.url,
        hlsPath: rtspConfig.hlsPath
    });
});

app.post('/api/start', (req, res) => {
    try {
        startRTSPToHLS();
        res.json({ success: true, message: 'RTSP to HLS conversion started' });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

app.post('/api/stop', (req, res) => {
    try {
        stopRTSPToHLS();
        res.json({ success: true, message: 'RTSP to HLS conversion stopped' });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

app.post('/api/config', (req, res) => {
    const { rtspUrl, segmentDuration, segmentMaxFiles } = req.body;
    
    if (rtspUrl) rtspConfig.url = rtspUrl;
    if (segmentDuration) rtspConfig.segmentDuration = parseInt(segmentDuration);
    if (segmentMaxFiles) rtspConfig.segmentMaxFiles = parseInt(segmentMaxFiles);
    
    res.json({ success: true, config: rtspConfig });
});

// 提供HLS文件
app.get('/hls/:file', (req, res) => {
    const filePath = path.join(hlsDir, req.params.file);
    if (fs.existsSync(filePath)) {
        res.sendFile(filePath);
    } else {
        res.status(404).send('File not found');
    }
});

// 主页面
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
    console.log(`Open http://localhost:${PORT} in your browser`);
    
    // 自动启动RTSP转换（可选）
    // startRTSPToHLS();
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('Shutting down server...');
    stopRTSPToHLS();
    process.exit(0);
});

process.on('SIGTERM', () => {
    console.log('Shutting down server...');
    stopRTSPToHLS();
    process.exit(0);
});
